package com.sczmgk.hotline_pzh.utils;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore.Images;

import com.sczmgk.hotline_pzh.MyApp;
import com.sczmgk.hotline_pzh.sp.SpfUtil;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtil {
	
	private static final String TAG = "FileUtil";
	/**
	 * 
	 */
	public static String ROOT_PATH = null;

	/**
	 * 公共资源下载缓存文件路径
	 */
	public static String RESOURCE_COMMON_CACHE_PATH = null;
	/**
	 * 用户文件资源下载缓存文件路径
	 */
	public static String RESOURCE_USER_FILE_CACHE_PATH = null;
	/**
	 * 用户图片资源下载缓存文件路径
	 */
	public static String RESOURCE_USER_IMAGE_CACHE_PATH = null;
	/**
	 * 用户DB路径
	 */
	public static String RESOURCE_USER_DB_CACHE_PATH = null;
	/**
	 * 用户录音资源下载缓存文件路径
	 */
	public static String RESOURCE_USER_RECORD_CACHE_PATH = null;
	/**
	 * 用户视频资源下载缓存文件路径
	 */
	public static String RESOURCE_USER_VIDEO_CACHE_PATH = null;
	
	/**
	 * 相册目录
	 */
	public static String COPY_FILE_PATH = null;
	
	/**
	 * 资源下载路径
	 */
	public static String RESOURCE_DOWNLOAD_PATH = null;
	/**
	 * 内存空间不足
	 */
	public static String SAVE_FILE_STATUS_MEMORY_ERROR = "MEMORY_ERROR";
	/**
	 * sdcard不存在
	 */
	public static String SAVE_FILE_STATUS_SDCARD_ERROR = "SDCARD_ERROR";
	/**
	 * 系统错误
	 */
	public static String SAVE_FILE_STATUS_SYSTEM_ERROR = "SYSTEM_ERROR";

	public static String IMAGE_TYPE_JPEG = "jpg";
	/**
	 * 初始化应用存储路径
	 * 
	 * @param context
	 */
	public static void initAppStoragePath(Context context) {
		
		FileUtil.ROOT_PATH = getAppStorageDir(context);
		MyLog.i(TAG,"取得App的rootpath是： "+FileUtil.ROOT_PATH);
		
		COPY_FILE_PATH =  Environment.getExternalStorageDirectory().toString();//相册目录
		if (null==COPY_FILE_PATH) {
			MyLog.i(TAG,"getSDCardDir      1");
			COPY_FILE_PATH = getSDCardDir();
		}
		COPY_FILE_PATH = COPY_FILE_PATH+File.separator+"DCIM"+File.separator+"camera";
		if (FileUtil.ROOT_PATH != null) {
			FileUtil.RESOURCE_COMMON_CACHE_PATH = FileUtil.ROOT_PATH+ File.separator + ".resource";
					
		}
		RESOURCE_DOWNLOAD_PATH = getStorageDir(context,false)+File.separator+"download";
		
		String userName = SpfUtil.getValue(context,SpfUtil.LAST_USERNAME, "temp").toString();
		
		initLoginStoragePath(userName);
	}

	/**
	 * 用户个人文件
	 * 
	 * @param userName
	 */
	public static void initLoginStoragePath(String userName) {
		
		if (FileUtil.ROOT_PATH != null) {
			FileUtil.RESOURCE_USER_DB_CACHE_PATH = FileUtil.ROOT_PATH+ File.separator + userName + File.separator + "database";
					
			FileUtil.RESOURCE_USER_FILE_CACHE_PATH = FileUtil.ROOT_PATH+ File.separator + userName + File.separator + "file";
					
			FileUtil.RESOURCE_USER_IMAGE_CACHE_PATH = FileUtil.ROOT_PATH+ File.separator + userName + File.separator + "image";
					
			FileUtil.RESOURCE_USER_RECORD_CACHE_PATH = FileUtil.ROOT_PATH+ File.separator + userName + File.separator + "record";
					
			FileUtil.RESOURCE_USER_VIDEO_CACHE_PATH = FileUtil.ROOT_PATH+ File.separator + userName + File.separator + "video";
					
		}
	}
    /**
     * 取得录音缓存路径
     * @param username
     * @return
     */
    public static String getUserRecordCacheDir(String username) {
        initLoginStoragePath(username);
        checkDirectory(new File(RESOURCE_USER_RECORD_CACHE_PATH));
        return RESOURCE_USER_RECORD_CACHE_PATH;
    }

    /**
     * 取得用户图片缓存路径
     * @param username
     * @return
     */
    public static String getUserImageCacheDir(String username) {
        initLoginStoragePath(username);        
        return RESOURCE_USER_IMAGE_CACHE_PATH;
    }
    
    /**
     * 取得上传投诉图片的临时路径 
     * @return
     */
    public static String getUploadPicTempFilePath() {
    	return getUserImageCacheDir(MyApp.loginUserUid+"");
    }
    /**
     * 取得登录用户头像路径
     * @return
     */
    public static String getLoginUserCaptureCacheFilePath() {
        return getUserImageCacheDir(MyApp.loginUserUid+"") + File.separator + "captureTemp.jpg";
    }

    /**
     * 根据用户名取得拍照头像的路径
     * @param username  用户名
     * @return
     */
    public static String getUserCaptureCacheFilePath(String username) {
        return getUserImageCacheDir(username) + File.separator + "captureTemp.jpg";
    }

	/**
	 * 根据功能编码取得功能的图片路径
	 * @param serviceCode 功能编码
	 * @return
	 */
	public static String getFunctionPicFilePath(String serviceCode) {
		return getUserImageCacheDir(serviceCode) + File.separator + "functionPic.jpg";
	}
    /**
     * 根据用户名及后缀取得拍照头像的路径 
     * @param username   用户名
     * @param postfix   后缀
     * @return
     */
    public static String getUserCaptureCacheFilePath(String username, String postfix) {
        return getUserImageCacheDir(username) + File.separator + "capture_temp_" + postfix + ".jpg";
    }

    /**
     * 根据用户名取得聊天背景的路径
     * @param username  用户名
     * @return
     */
    public static String getUserBgImageFilePath(String username) {
        return getUserImageCacheDir(username) + File.separator + "chat_bg.png";
    }

    /**
     * 根据用户名及后缀取得聊天背景的路径 
     * @param username   用户名
     * @param postfix   后缀
     * @return
     */
    public static String getUserBgImageFilePath(String username, String postfix) {
        return getUserImageCacheDir(username) + File.separator + "chat_bg_" + postfix + ".png";
    }

    /**
     * 检查路径是否正确
     * @param dir
     */
    public static void checkDirectory(File dir) {
        if (dir.exists()) {
            if (!dir.isDirectory() && !dir.delete() && !dir.mkdirs()) {
                throw new RuntimeException("create file(" + dir + ") fail.");
            }
        } else if (!dir.mkdirs()) {
            throw new RuntimeException("create file(" + dir + ") fail.");
        }
    }
	
	/**
	 * 获取APP 存储的路径
	 * 
	 * @param context
	 * @return
	 */
	public static String getAppStorageDir(Context context) {
		// 获取Android程序在Sd上的保存目录约定 当程序卸载时，系统会自动删除。
		File f = context.getExternalFilesDir(null);
		// 如果约定目录不存在
		if (f == null) {
			// 获取外部存储目录即 SDCard
			return getStorageDir(context);
		} else {
			String storageDirectory = f.getAbsolutePath();
			MyLog.d(TAG,"项目存储路径采用系统给的路径地址  storageDirectory:"+ storageDirectory);
			return storageDirectory;
		}

	}
	/**
	 * 获取可用的sdcard路径
	 * @param context
	 * @return
	 */
	public static String getStorageDir(Context context){
		return getStorageDir(context, true);
	}
	
	/**
	 * 获取可用的sdcard路径
	 * @param context
	 * @param isAllowUseCache  是否允许缓存
	 * @return
	 */
	public static String getStorageDir(Context context,boolean isAllowUseCache){
		// 获取外部存储目录即 SDCard
		String storageDirectory = Environment.getExternalStorageDirectory()
				.toString();
		File fDir = new File(storageDirectory);
		// 如果sdcard目录不可用
		if (!fDir.canWrite()) {
			// 获取可用
			MyLog.i(TAG,"getSDCardDir      2");
			storageDirectory = getSDCardDir();
			if (storageDirectory != null) {
				storageDirectory = storageDirectory + File.separator
						+ "lezheng" + File.separator
						+ "lezhengchat";
				MyLog.d(TAG,"项目存储路径采用自动找寻可用存储空间的方式   storageDirectory:"
						+ storageDirectory);
				return storageDirectory;

			} else {
				if(isAllowUseCache){
					MyLog.e(TAG,"没有找到可用的存储路径  采用cachedir");
					return context.getCacheDir().toString();
				}else{
					return null;
				}
			}
		} else {
			storageDirectory = storageDirectory + File.separator + "pingan"
					+ File.separator
					+ "pachat";
			MyLog.d(TAG,"项目存储路径采用sdcard的地址   storageDirectory:"
					+ storageDirectory);
			return storageDirectory;
		}
	}

	/**
	 * 是否为文件路径
	 * @param filePath
	 * @return
	 */
	public static boolean isFile(String filePath){
		if(filePath!=null){
			if(new File(filePath).isFile()){
				return true;
			}
		}
		return false;
	}
	
	/**
	 *  获取一个可用的存储路径（可能是内置的存储路径）
	 * 
	 * @return  可用的存储路径
	 */
	private static String getSDCardDir() {
		String pathDir = null;
		// 先获取内置sdcard路径
		File sdfile = Environment.getExternalStorageDirectory();
	    MyLog.e(TAG,"sdfile  =  "+sdfile.toString());
		// 获取内置sdcard的父路径
		File parentFile = sdfile.getParentFile();
	    MyLog.e(TAG,"parentFile  =  "+parentFile.toString());
		// 列出该父目录下的所有路径
		File[] listFiles = parentFile.listFiles();
		// 如果子路径可以写 就是拓展卡（包含内置的和外置的）
        if(listFiles == null){
        	MyLog.e(TAG,"listFile  =  "+listFiles);
        }
		long freeSizeMax = 0L;
		for (int i = 0; i < listFiles.length; i++) {
			if (listFiles[i].canWrite()) {
				// listFiles[i]就是SD卡路径
				String tempPathDir = listFiles[i].getAbsolutePath();
				long tempSize = getSDFreeSize(tempPathDir);
				if (tempSize > freeSizeMax) {
					freeSizeMax = tempSize;
					pathDir = tempPathDir;
				}
			}
		}
		return pathDir;
	}

	/**
	 * 获取可用的sdcard路径
	 * @param filePath
	 * @return
	 */
    public static long getSDFreeSize(String filePath) {

        try {
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }

            android.os.StatFs statfs = new android.os.StatFs(filePath);

            long nBlocSize = statfs.getBlockSize(); // 获取SDCard上每个block的SIZE

            long nAvailaBlock = statfs.getAvailableBlocks(); // 获取可供程序使用的Block的数量

            long nSDFreeSize = nAvailaBlock * nBlocSize; // 计算 SDCard
            // 剩余大小B
            return nSDFreeSize;
        } catch (Exception ex) {
            ex.printStackTrace();
            MyLog.d(TAG,"httpFrame threadName:" + Thread.currentThread().getName()
                    + " getSDFreeSize  无法计算文件夹大小 folderPath:" + filePath);
        }

        return -1;
    }
	/**
	 * 清除缓存文件
	 * @param context
	 */
    public static void clearAllData(Context context) {
        File file = new File("/data/data/" + context.getPackageName());
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            File f = files[i];
            if (!f.getName().equals("lib")) {
                deleteFile(f);
            }
        }
        File file2 = new File(ROOT_PATH);
        deleteFile(file2);
    }

	  /**
	   * 删除文件
	   * @param file
	   */
    public static void deleteFile(File file) {
        if (file.isDirectory()) {
            MyLog.v(TAG, "deleteFile  正在删除文件夹：" + file.getPath());
            File[] files = file.listFiles();
            if (files.length >= 1) {
            	MyLog.v(TAG, "deleteFile  文件夹 包含"+files.length +"个File");
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            boolean ch = file.delete();
            MyLog.v(TAG, "deleteFile  删除文件夹("+file.getPath()+")：" +ch);
        } else {
        	MyLog.v(TAG, "deleteFile  正在删除文件：" + file.getPath());
            boolean ch = file.delete();
            MyLog.v(TAG, "deleteFile  删除文件("+file.getPath()+")：" +ch);
        }
    }
    /**
     * 取得文件名
     * @param filePath
     * @return
     */
    public static String getFileName(String filePath) {
        if (filePath.length() > 0 && filePath != null) { // --截取文件名
            int i = filePath.lastIndexOf("/");
            return filePath.substring(i + 1, filePath.length());
        }
        return null;
    }

    /**
     * Copy图片文件到SdCard
     * @param copyFilePath
     * @param saveFloderPath
     * @return  sdCard路径
     */
    public static String copyImageFile2SdCard(String copyFilePath, String saveFloderPath) {
        if (saveFloderPath == null || saveFloderPath.trim().equals("")) {
            return SAVE_FILE_STATUS_SDCARD_ERROR;
        }
        File srcPath = new File(copyFilePath);
        // 如果空间足够
        if (makeDir(saveFloderPath) && srcPath.length() < getSDFreeSize(saveFloderPath)) {            
            File destPath = new File(saveFloderPath + File.separator + getFileName(copyFilePath) + ".jpg");

            InputStream in = null;
            OutputStream out = null;
            try {
                in = new FileInputStream(srcPath);
                out = new FileOutputStream(destPath);

                byte[] buffer = new byte[1024];

                int length;

                while ((length = in.read(buffer)) > 0) {
                    out.write(buffer, 0, length);
                }
                return destPath.getAbsolutePath();
            } catch (Exception e) {
                e.printStackTrace();
                return SAVE_FILE_STATUS_SYSTEM_ERROR;
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                    if (out != null) {
                        out.flush();
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

        } else {
            return SAVE_FILE_STATUS_MEMORY_ERROR;
        }
    }

    private static boolean makeDir(String dir) {
        File destFloderPath = new File(dir);
        if (!destFloderPath.isDirectory()) {
            return destFloderPath.mkdirs();
        }
        return true;
    }

    /**
     * 
     * 清除文件的回调
     *
     */
    public static interface ClearDataCallback {
        public void clearDatafinish();
    }
    
    /**
	 * 保存图片至相册
	 * 
	 * @param cr   要保存内容的上下文
	 * @param title  标题
	 * @param dateTaken  时间戳
	 * @param directory  目录
	 * @param filename  文件名
	 * @param source  图片文件
	 * @return 返回图片的路径
	 */
	public static Uri addImage(ContentResolver cr, String title,
			long dateTaken, String directory, String filename, Bitmap source) {
		File file = null;
//		if (!DeviceUtil.isExistsSDCard() || filename == null)
//			return null;
		OutputStream outputStream = null;
		directory = getDir() + directory;
		String filePath = directory + "/" + filename;
		try {
			File dir = new File(directory);
			if (!dir.exists())
				dir.mkdirs();
			file = new File(filePath);
			outputStream = new FileOutputStream(file);
			if (source != null) {
				source.compress(CompressFormat.JPEG, 100, outputStream);
			} else
				return null;
		} catch (FileNotFoundException ex) {
			return null;
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		// 插入数据
		long size = new File(directory, filename).length();
		ContentValues values = new ContentValues(7);
		values.put(Images.Media.TITLE, title);
		values.put(Images.Media.DISPLAY_NAME, filename);
		values.put(Images.Media.DATE_TAKEN, dateTaken);
		values.put(Images.Media.MIME_TYPE, "image/jpeg");
		values.put(Images.Media.ORIENTATION, 0);
		values.put(Images.Media.DATA, filePath);
		values.put(Images.Media.SIZE, size);

		return cr.insert(Images.Media.EXTERNAL_CONTENT_URI, values);

	}

	/**
	 *  得到相册的目录
	 */
	private static String getDir() {
		return Environment.getExternalStorageDirectory().toString() + "/DCIM/";
	}
	
    /**
     * 用时间戳生成照片/视频名称
     * 
     * @param str jpg,png,3gp等格式
     * @return
     */
    public static String getImageAndVideoFileName(String str) {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
        return dateFormat.format(date) + "." + str;
    }
    /////////////////////////////////////////////////////////////////////////////////////////////
	private static final Object mLockObject = new Object();
//	private static final String TAG = FileUtil.class.getSimpleName();
//	public static String ROOT_PATH = null;
	public static boolean avaiableSDCard() {
		String status = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(status))
			return true;
		else
			return false;
	}

	/**
	 * 存文件到SD卡
	 * @param fileName
	 * @param inStream
	 * @return
	 * @throws IOException
	 */
	public static boolean saveFile2SDCard(String fileName, InputStream inStream)
			throws IOException {
		boolean flag = false;
		FileOutputStream fs = null;
		
		try {
			if (!Tools.isEmpty(fileName) && inStream != null) {
				
				File file = newFileWithPath(fileName.toString());
				if (file.exists()) {
					file.delete();
				}
				
				fs = new FileOutputStream(file);
				byte[] buffer = new byte[1024];
				int len = -1;

				while ((len = inStream.read(buffer)) != -1) {
					fs.write(buffer, 0, len);
				}

				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fs != null)
				fs.close();
		}

		return flag;
	}

	/**
	 * 存文件到SD卡
	 * @param fileName
	 * @param dataBytes
	 * @return
	 * @throws IOException
	 */
	public static boolean saveFile2SDCard(String fileName, byte[] dataBytes)
			throws IOException {
		boolean flag = false;
		FileOutputStream fs = null;
		try {
			if (!Tools.isEmpty(fileName)) {
				File file = newFileWithPath(fileName.toString());
				if (file.exists()) {
					file.delete();
				}
				fs = new FileOutputStream(file);
				fs.write(dataBytes, 0, dataBytes.length);
				fs.flush();
				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fs != null)
				fs.close();
		}

		return flag;
	}
	/**
	 * 将Stream转成字节数组
	 * @param inStream
	 * @return
	 * @throws IOException
	 */
	public static byte[] readStream(InputStream inStream) throws IOException {
		ByteArrayOutputStream outstream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = -1;
		while ((len = inStream.read(buffer)) != -1) {
			outstream.write(buffer, 0, len);
		}

		return outstream.toByteArray();
	}
	/**
	 * 将Stream转成字符串
	 * @param inStream
	 * @return
	 * @throws IOException
	 */
	public static String readStreamToString(InputStream inStream) throws IOException {
		InputStreamReader isr = new InputStreamReader(inStream);
		BufferedReader br = new BufferedReader(isr);
		
		StringBuffer sb = new StringBuffer();
		String s = null;
		while((s = br.readLine()) != null){
			sb.append(s);
			sb.append("\r\n");
		}
		br.close();
		return sb.toString();
	}
	private static File newFileWithPath(String filePath){
		if(Tools.isEmpty(filePath)){
			return null;
		}
		
		int index = filePath.lastIndexOf(File.separator);
		
		String path = "";
		if(index != -1){
			path = filePath.substring(0, index);
			if(!Tools.isEmpty(path)){
				File file = new File(path.toString());
				if (!file.exists() && !file.isDirectory()) {
					boolean flag = file.mkdirs();
					if (flag) {
					} else {
					}
				}
			}
		}
		return new File(filePath);
	}
	
	/**
	 * 删除文件
	 * @param fileName
	 * @return  是否成功删除
	 */
    public static boolean delete(String fileName){   
        File file = new File(fileName);   
        if(!file.exists()){   
            return false;   
        }else{   
            if(file.isFile()){   
                   
                return deleteFile(fileName);   
            }else{   
                return deleteDirectory(fileName);   
            }   
        }   
    }   
    /**   
     * 删除文件
     * @param fileName  
     * @return  是否成功删除
     */
    public static boolean deleteFile(String fileName){   
    	return deleteFile(fileName, false);
    }   
    /**
     * 删除文件
     * @param fileName 
     * @param isTemp
     * @return
     */
    public static boolean deleteFile(String fileName,boolean isTemp){   
    	if(fileName!=null){
    		String logFile  = "";
    		if(isTemp){
    			logFile= "temp";
    		}else{
    			logFile= "file";
    		}
            File file = new File(fileName);   
            if(file.isFile() && file.exists()){   
                file.delete();   
                return true;   
            }else{   
                return false;   
            }
    	}
    	return false;
    	
    }   
       
    /**
     * 根据路径删除文件
     * @param dir
     * @return
     */
    public static boolean deleteDirectory(String dir){   
        if(!dir.endsWith(File.separator)){   
            dir = dir+File.separator;   
        }   
        File dirFile = new File(dir);   
        if(!dirFile.exists() || !dirFile.isDirectory()){   
            return false;   
        }   
        boolean flag = true;   
        File[] files = dirFile.listFiles();   
        for(File file : files){   
            if(file.isFile()){   
                flag = deleteFile(file.getAbsolutePath());   
                if(!flag){   
                    break;   
                }   
            }   
            else{   
                flag = deleteDirectory(file.getAbsolutePath());   
                if(!flag){   
                    break;   
                }   
            }   
        }   
           
        if(!flag){   
            return false;   
        }   
        
        if(dirFile.delete()){   
            return true;   
        }else{   
            return false;   
        }   
    }
    
    /**
     * 取得SD卡剩余空间
     * @return
     */
    public static long getSDFreeSize(){
    	
    	return getSDFreeSize(Environment.getExternalStorageDirectory().toString());
    }
    /**
     * 切割文件名
     * @param prePath
     * @param fileNamePath
     * @return
     */
    public static String splitJointPath(String prePath,String fileNamePath){
    	if(prePath == null || fileNamePath == null){
    		return "";
    	}
    	String path = "";
    	if(prePath.endsWith("/")){
    		if(fileNamePath.startsWith("/")){
    			path = prePath+fileNamePath.substring(1);
    		}else{
    			path = prePath+fileNamePath;
    		}
    	}else{
    		if(fileNamePath.startsWith("/")){
    			path = prePath+fileNamePath;
    		}else{
    			path = prePath+"/"+fileNamePath;
    		}
    	}
    	return path;
    }
    /**
     * 取得图片的长度
     * @param bitmap
     * @return
     */
    public static long getBitmapLength(Bitmap bitmap){
    	return bitmap.getRowBytes()*bitmap.getHeight();
    }
    /**
     * 存入Bitmap(此方法存入图片为.jpg,或.png 格式 )
     * 　注：如果bitmpa 传入前进行质量压缩，如字节数组的大小为30k,此方法中的  bm.compress(format,100,fos)将会使图片的大小存为100k以上
     *   将参数设置成 bm.compress(format,30,fos) 图片大小将为 50k 左右
     * @param fileRootPath   文件路径
     * @param bm  bitMap
     * @param format  格式
     * @param extension
     * @return  返回图片的路径
     */
	public static String saveBitmap(String fileRootPath,Bitmap bm,CompressFormat format,String extension){
		
		if(createFolder(fileRootPath)){
			long bitmapSize=getBitmapLength(bm);
			
			FileOutputStream fos = null;
			if(getSDFreeSize(fileRootPath)<=bitmapSize){
				return null;
			}
			
			try{
				String filePath = fileRootPath +File.separator+getTimeMillisFileName();
				if(extension!=null&&extension.length()>0){
					filePath = filePath+"."+extension;
				}
				
				File file=new File(filePath);
				file.createNewFile();//创建一个空文件
				fos=new FileOutputStream(file);
                //质量压缩
				bm.compress(format, 30, fos);//将图片写入文件流
				return filePath;
				  
			}catch (Exception e) {
				e.printStackTrace();
			}finally{
				try {
					if(fos != null){
							fos.flush();
							fos.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}else{
		}
		
		return null;
	}
	/**
	 *  将字节数组存入文件
	 * @param fileRootPath
	 * @param extension
	 * @param bytes
	 * @return  返回文件路径
	 */
	public static String saveFile(String fileRootPath,String extension,byte[] bytes){
		
		
		return saveFile(fileRootPath, extension, bytes, false);
	}
    /**
     * 将字节数组存入文件
     * @param fileRootPath
     * @param extension
     * @param bytes
     * @param isTemp  是否为临时文件
     * @return  返回文件路径
     */
	public static String saveFile(String fileRootPath,String extension,byte[] bytes,boolean isTemp){
		String logFile  = "";
		if(isTemp){
			logFile= "temp";
		}else{
			logFile= "file";
		}
		
		
		if(createFolder(fileRootPath)){
			long bitmapSize=bytes.length;
			
			FileOutputStream fos = null;
			if(getSDFreeSize(fileRootPath)<=bitmapSize){
				return null;
			}
			
			try{
				String filePath = fileRootPath +File.separator+getTimeMillisFileName()+"."+extension;
				File file=new File(filePath);
				file.createNewFile();
				
				fos=new FileOutputStream(file);
				fos.write(bytes,0,bytes.length);
				return filePath;
				  
			}catch (Exception e) {
				e.printStackTrace();
			}finally{
				try {
					if(fos != null){
						fos.flush();
						fos.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}else{
		}
		
		return null;
	}
	/**
	 * 创建文件夹
	 * @param folderPath
	 * @return
	 */
	public static boolean createFolder(String folderPath){
		File file=new File(folderPath);
		if(!file.exists()){
			return file.mkdirs();
		}
		return true;
	}
	
	/**
	 * 根据文件路径取得文件大小
	 * @param filePath
	 * @return  文件大小
	 */
	public static long getFileLength(String filePath){
		if(filePath!=null){
			File file = new File(filePath);
			if(file.isFile()){
				return file.length();
			}
		}
		return -1;
	}
	public static String getExtensionName(String filePath){
		if(filePath==null){
			return null;
		}
		
		int indexSeparator = filePath.lastIndexOf(File.separator);
		if(filePath.indexOf(".", indexSeparator)<0){
			return null;
		}
		
		if(filePath!=null&&filePath.length()>0 ){ 
			int i = filePath.lastIndexOf(".");
			if(i>=0){
				return filePath.substring(i+1, filePath.length());
			}else{
				return "";
			}
		} 
		return null;
	}
	/**
	 * 取得文件夹路径
	 * @param filePath
	 * @return  
	 */
	public static String getFolderPath(String filePath){
		if(filePath.length()>0 && filePath!=null){  
			int i = filePath.lastIndexOf("/");
			return filePath.substring(0, i);
		} 
		return null;
	}
	/**
	 *  取得压缩图片的路径
	 * 
	 * @param image
	 * @param savePath
	 * @param extension
	 * @return
	 * @throws IOException
	 */
	public static String compressImagePath(Bitmap image,String savePath,String extension) throws IOException {   
		byte[] byteArrary = compressImageByte(image,extension);
		String filePath = FileUtil.saveFile(savePath, extension, byteArrary,true);
		return filePath;
	}
	/**
	 * 压缩图片
	 * @param image
	 * @param extension
	 * @return  返回压缩图片的数组
	 * @throws IOException
	 */
	public static byte[] compressImageByte(Bitmap image,String extension) throws IOException {   
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		CompressFormat format = null;
		if(BitmapUtils.EXTENSION_IMG_JPEG.equals(extension)){
			format = CompressFormat.JPEG;
		}else{
			format = CompressFormat.PNG;
		}
		image.compress(format, 100, baos);
		int options = 100;   
		while ( baos.toByteArray().length / 1024>150) {         
			baos.reset();
			image.compress(format, options, baos);
		
			if(options<=40){
				break;
			}
			options -= 10;
		}
		byte[] byteArrary =  baos.toByteArray();
		baos.flush();
		baos.close();
		System.gc();
		return byteArrary;
	}
	/**
	 * 复制文件
	 * @param srcPath  源路径
	 * @param destPath  目的路径
	 * @return  是否复制成功
	 */
	public static boolean copyFile(File srcPath,File destPath){
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(srcPath);
			out = new FileOutputStream(destPath);

			byte[] buffer = new byte[1024];

			int length;
			
			while ((length = in.read(buffer)) > 0) {
				out.write(buffer, 0, length);
			}
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				if(in!=null){
					in.close();
				}
				if(out!=null){
					out.flush();
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		return false;
	}
	public static String getTimeMillisFileName(){
		synchronized (mLockObject) {
			long curTime = System.currentTimeMillis();
			while(true){
				long time = System.currentTimeMillis();
				if(time-curTime>0){
					return ""+time;
				}
			} 
		}
	}
	
	/**
	 * 初始化root路径
	 * @param context
	 */
	public static void initTempRootPath(Context context){
		ROOT_PATH = getAppStorageDir(context);
	}
}
